package com.jflm.util;


import java.security.PrivateKey;
import java.security.cert.X509Certificate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cat.util.charset.Base64;


public class SignHandlerTest {
	private static Log _log = LogFactory.getLog(SignHandlerTest.class);

	public static boolean doCheckSign(String merId, String signStr, String sign)
			throws Exception {
		try {
			_log.debug("# 开始验证签名信息");
			String certFile = PropertiesUtils.getProperty(merId+".certFilePath");
			_log.debug("#证书路径"+certFile);
			byte[] certData = FileUtil.getFileContent(certFile);

			X509Certificate cert = SignUtil.genCertificate(certData);

			byte[] signData = Base64.decode(sign);
			return SignUtil.verify(cert, signStr.getBytes(), signData);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}

	}

	
	public static String doGenerateSign(String dataString) throws Exception {
		try {
			_log.debug("# 开始生成签名信息");
		
			String keyFile = PropertiesUtils.getProperty("certFilePath");
			_log.info("keyFile:"+keyFile);
			byte[] key = FileUtil.getFileContent(keyFile);
			PrivateKey pk = SignUtil.genPrivateKey(key);
			byte[] signData = SignUtil.sign(pk, dataString.getBytes());
			String pemSignData = Base64.encode(signData);
			return pemSignData;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}

	}
	
	
	/**
	 * 签名  
	 * @param keyfilepath  签名证书路径
	 * @param dataString   签名串
	 * @return
	 * @throws SignEncException
	 */
	public static String doGenerateSign(String merid,String dataString) throws Exception {
		try {
			String keyfilepath = PropertiesUtils.getProperty(merid+".certFilePath");
			_log.debug(merid+"# 证书路径"+keyfilepath);			
			byte[] key = FileUtil.getFileContent(keyfilepath);
			
			PrivateKey pk = SignUtil.genPrivateKey(key);
			
			byte[] signData = SignUtil.sign(pk, dataString.getBytes());
			
			String pemSignData = Base64.encode(signData);
			
			return pemSignData;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		
	}

}
